package com.ibpd.shopping.web.controller.manage;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hsqldb.lib.FileUtil;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.common.FileCommon;
import com.ibpd.henuocms.common.FileEncryptAndDecryptUtil;
import com.ibpd.henuocms.common.IbpdCommon;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.common.MD5;
import com.ibpd.henuocms.common.Pinyin4jUtil;
import com.ibpd.henuocms.entity.UserEntity;
import com.ibpd.henuocms.exception.IbpdException;
import com.ibpd.henuocms.service.user.IUserService;
import com.ibpd.henuocms.service.user.UserServiceImpl;
import com.ibpd.henuocms.web.controller.manage.BaseController;
import com.ibpd.shopping.entity.TenantEntity;
import com.ibpd.shopping.entity.UserTenantEntity;
import com.ibpd.shopping.service.tenant.ITenantService;
import com.ibpd.shopping.service.tenant.TenantServiceImpl;
import com.ibpd.shopping.service.userTenant.IUserTenantService;
import com.ibpd.shopping.service.userTenant.UserTenantServiceImpl;

@Controller
public class Tenant extends BaseController {
	@RequestMapping("Manage/Tenant/index.do")
	public String index(Model model,HttpServletRequest req,String type) throws IOException{
		model.addAttribute("pageTitle","商户管理");
		model.addAttribute("type",type);
		
		return "manage/s_tenant/index";
	}
	@RequestMapping("Manage/Tenant/initUser.do")
	public String initUser(Model model,HttpServletRequest req,Long id){
		model.addAttribute("pageTitle","初始商户用户");
		model.addAttribute("tenantId",id);
		ITenantService ts=(ITenantService) getService(TenantServiceImpl.class);
		TenantEntity te=ts.getEntityById(id);
		if(te!=null)
			if(StringUtil.isBlank(te.getEntFullName()))
				model.addAttribute("defaultUserName",Pinyin4jUtil.getPinYinHeadChar(te.getEntFullName()));
			else
				model.addAttribute("defaultUserName","tenantUser"+te.getId());
		model.addAttribute("defaultPassword","123456");
		return "manage/s_tenant/initUser";
	}
	@RequestMapping("Manage/Tenant/doInitUser.do")
	public void doInitUser(Long id,String userName,String password,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		if(id==null || id<=0){
			super.printMsg(resp, "-1", "-1", "ID不能为空");
		}
		ITenantService ts=(ITenantService) getService(TenantServiceImpl.class);
		TenantEntity te=ts.getEntityById(id);
		if(te==null){
			super.printMsg(resp, "-2", "-2", "没有这个商户");
		}
		IUserTenantService utServ=(IUserTenantService) getService(UserTenantServiceImpl.class);
		UserTenantEntity ut=utServ.getUserTenantContrastByTenantId(te.getId());
		IUserService userServ=(IUserService) getService(UserServiceImpl.class);
		if(ut!=null){
			//这里的逻辑，如果用户跟供应商本身已经有对照关系了，name就直接解除关系，删除相应信息
			userServ.deleteByPK(ut.getUserId());
			utServ.deleteByPK(ut.getId());
		}
		//重新建立关系
		UserEntity ue=new UserEntity();
		ue.setUserName(userName);
		ue.setPassword(MD5.md5(password));
		ue.setState(99);
		userServ.saveEntity(ue);
		UserTenantEntity nt=new UserTenantEntity();
		nt.setTenantId(te.getId());
		nt.setUserId(ue.getId());
		utServ.saveEntity(nt);
		super.printMsg(resp, "99", nt.getId()+"", "执行成功");
	
	}
	@RequestMapping("Manage/Tenant/list.do")
	public void list(HttpServletResponse resp,String type,String order,Integer page,Integer rows,String sort,String queryString,HttpServletRequest req) throws IOException{
		ITenantService tenantServ=(ITenantService) getService(TenantServiceImpl.class);
		String query="";
		if(type!=null){
			if(type.trim().toLowerCase().equals("ent")){
				query=" tenantType=0";
			}else if(type.trim().toLowerCase().equals("sing")){
				query=" tenantType=1";
			}
		}
//		tenantServ.getDao().clearCache();
		super.getList(req, tenantServ, resp, order, page, rows, sort, query);
	}
	@RequestMapping("Manage/Tenant/props.do")
	public String props(Long id,String type,Model model) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(id==null || id<0L){
			model.addAttribute("errorMsg","参数错误");
			return super.ERROR_PAGE;
		}
		type=type==null?"":type;
		ITenantService tenantServ=(ITenantService) getService(TenantServiceImpl.class);
		TenantEntity ce=tenantServ.getEntityById(id);
		if(ce==null){
			model.addAttribute("errorMsg","没有该类别");
			return super.ERROR_PAGE;
		}
		model.addAttribute("type",getIntType(type));
		model.addAttribute("pageTitle","参数设置");
		if(type.toLowerCase().trim().equals("ent"))
			model.addAttribute("htmls",super.getHtmlString(ce, "tenant.ent.edit.field"));
		else
			model.addAttribute("htmls",super.getHtmlString(ce, "tenant.sing.edit.field"));
		model.addAttribute("entity",ce);
		return "manage/s_tenant/props";
	}	
	@RequestMapping("Manage/Tenant/saveProp.do")
	public void saveProps(Long id,String field,String value,HttpServletResponse resp) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException{
		if(id!=null && id!=-1){
			ITenantService tenantServ=(ITenantService) getService(TenantServiceImpl.class);
			TenantEntity cata=tenantServ.getEntityById(id);
				if(cata!=null){
					//先确定参数类型
					Method tmpMethod=cata.getClass().getMethod("get"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{});
					
					
					Method method=cata.getClass().getMethod("set"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{tmpMethod.getReturnType()});
					Object val=getValue(value,tmpMethod.getReturnType().getSimpleName());
					IbpdLogger.getLogger(this.getClass()).info("value="+val);
					method.invoke(cata, val);
					tenantServ.saveEntity(cata);
//					tenantServ.getDao().clearCache();
					super.printMsg(resp, "99", cata.getId().toString(), "保存成功");		
				}else{
					super.printMsg(resp, "-1", "", "没有该类别");
				}
		}else{
			super.printMsg(resp, "-2", "", "参数错误");			
		}
	}
	private Integer getIntType(String type){
		if(type==null)
			return null;
		if(type.toLowerCase().trim().equals("ent")){
			return TenantEntity.TenantType_ent;
		}else{
			return TenantEntity.TenantType_sing;
		}
	}
	@RequestMapping("Manage/Tenant/toAdd.do")
	public String toAdd(Model model,String type,HttpServletResponse resp) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{

		model.addAttribute("pageTitle","添加");
		if(type==null){
			model.addAttribute("msg","参数错误");
			return ERROR_PAGE;
		}
		model.addAttribute("type",getIntType(type));
		if(type.trim().toLowerCase().equals("ent"))
			model.addAttribute("htmls",super.getHtmlString(null, "tenant.ent.add.field"));
		else
			model.addAttribute("htmls",super.getHtmlString(null, "tenant.sing.add.field"));
		return "manage/s_tenant/add";
	}
	@RequestMapping("Manage/Tenant/toEdit.do")
	public String toEdit(Long id,String  type,Model model,HttpServletResponse resp) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(id==null){
			return this.ERROR_PAGE;
		}
		ITenantService tenantServ=(ITenantService) getService(TenantServiceImpl.class);
		TenantEntity cata=tenantServ.getEntityById(id);
		model.addAttribute("type",getIntType(type));
		if(cata==null){
			model.addAttribute("errorMsg","没有该类别");
			return this.ERROR_PAGE;
		}
		model.addAttribute("pageTitle","编辑");
		if(type==null){
			model.addAttribute("msg","参数错误");
			return ERROR_PAGE;
		}
		if(type.trim().toLowerCase().equals("ent"))
			model.addAttribute("htmls",super.getHtmlString(cata, "tenant.ent.edit.field"));
		else
			model.addAttribute("htmls",super.getHtmlString(cata, "tenant.sing.edit.field"));
		model.addAttribute("entity",cata);
		return "manage/s_tenant/edit";
	}
	@RequestMapping("Manage/Tenant/doEdit.do")
	public void doEdit(TenantEntity entity,HttpServletResponse resp) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(entity!=null && entity.getId()!=null && entity.getId()!=-1L){
			
			ITenantService tenantServ=(ITenantService) getService(TenantServiceImpl.class);
			TenantEntity cata=tenantServ.getEntityById(entity.getId());
			if(cata==null){
				super.printMsg(resp, "-1", "", "没有该商户");
				return;
			}else{
				swap(entity,cata);
				tenantServ.saveEntity(cata);
				super.printMsg(resp, "99", cata.getId().toString(), "保存成功");
				return;
			}
		}else{
			super.printMsg(resp, "-2", "", "参数错误");
			return;
		}
		
	}
	@RequestMapping("Manage/Tenant/doAdd.do")
	public void doAdd(TenantEntity entity,HttpServletResponse resp) throws IOException{
		
		if(entity.getEntFullName().trim().equals("")){
			super.printMsg(resp, "-1", "-1", "参数错误");
			return;
		}
		ITenantService tenantServ=(ITenantService) getService(TenantServiceImpl.class);
		tenantServ.saveEntity(entity);	
		super.printMsg(resp, "99", "-1", "保存成功");
		 
	}
	@RequestMapping("Manage/Tenant/delTmpLicenceImg.do")
	public void delTmpLicenceImg(Long id,HttpServletResponse resp,HttpServletRequest req) throws IOException{
		id=(id==null)?-1L:id;
		ITenantService cataServ=(ITenantService) getService(TenantServiceImpl.class);
		TenantEntity t=cataServ.getEntityById(id);
		if(t==null){
			super.printMsg(resp, "-1", "", "没有选择项");	
			return;
		}
		if(t.getStatus().equals(TenantEntity.TenantStatus_unPass)){
			super.printMsg(resp, "99", "99", "ok" +
			"");
		}else if(t.getStatus().equals(TenantEntity.TenantStatus_passed)){
			if(t.getLicenceFilePath()==null || t.getLicenceFilePath().trim().equals("")){
				super.printMsg(resp, "99", "99", "ok" +
				"");
			}
			String tmpPath=t.getLicenceFilePath().substring(0,t.getLicenceFilePath().lastIndexOf("."))+"new"+t.getLicenceFilePath().substring(t.getLicenceFilePath().lastIndexOf("."));
			FileCommon.deleteFile(req.getRealPath(tmpPath.replace(req.getContextPath(), "")));
			super.printMsg(resp, "99", "99", "ok" +
					"");	
		}
	}
	@RequestMapping("Manage/Tenant/doDel.do")
	public void doDel(String ids,HttpServletResponse resp) throws IOException{
		if(StringUtil.isBlank(ids)){
			super.printMsg(resp, "-1", "", "没有选择项");	
		}
		ITenantService cataServ=(ITenantService) getService(TenantServiceImpl.class);
		cataServ.batchDel(ids);
		super.printMsg(resp, "99", "", "操作成功");	
	}
	@RequestMapping("Manage/Tenant/viewLicenceImage.do")
	public String viewLicenceImage(Long id,Model model,HttpServletResponse resp,HttpServletRequest req) throws NumberFormatException, Exception{
		if(id==null || id<=0){
			model.addAttribute("errorMsg","没有选择项");
			return this.ERROR_PAGE;
		}
		ITenantService cataServ=(ITenantService) getService(TenantServiceImpl.class);
		TenantEntity t=cataServ.getEntityById(id);
		if(t==null){
			model.addAttribute("errorMsg","没有选择项");
			return this.ERROR_PAGE;
		}
		String imgPath="";
		if(t.getStatus().equals(TenantEntity.TenantStatus_unPass)){
			imgPath=t.getLicenceFilePath();
		}else if(t.getStatus().equals(TenantEntity.TenantStatus_passed)){
			if(t.getLicenceFilePath()==null || t.getLicenceFilePath().trim().equals("")){
				model.addAttribute("tenantId",id);
				model.addAttribute("imgPath",req.getContextPath()+"/images/noimage.jpg");
				return "manage/s_tenant/view";
			}
			String l=IbpdCommon.getInterface().getPropertiesValue("fileEncryptLength");
			if(l==null)
				throw new IbpdException("fileEncryptLength为空");
			if(t.getLicenceFilePath()==null || t.getLicenceFilePath().trim().equals("")){
				imgPath=req.getContextPath()+"/images/noimage.jpg";
			}else{
				if(t.getLicenceFilePath().lastIndexOf(".")==-1){
					imgPath=req.getContextPath()+"/images/noimage.jpg";
				}else{
					String tmpPath=t.getLicenceFilePath().substring(0,t.getLicenceFilePath().lastIndexOf("."))+"new"+t.getLicenceFilePath().substring(t.getLicenceFilePath().lastIndexOf("."));
					FileEncryptAndDecryptUtil.decrypt(req.getRealPath(t.getLicenceFilePath().replace(req.getContextPath(), "")), req.getRealPath(tmpPath.replace(req.getContextPath(), "")),Integer.valueOf(l));
					imgPath=tmpPath;								
				}
			}
				
		}else{
			imgPath=t.getLicenceFilePath();
		}
		model.addAttribute("tenantId",id);
		model.addAttribute("imgPath",imgPath);
		return "manage/s_tenant/view";
	}
	@RequestMapping("Manage/Tenant/status.do")
	public void status(String ids,HttpServletResponse resp,HttpServletRequest req) throws Exception{
		if(StringUtil.isBlank(ids)){
			super.printMsg(resp, "-1", "", "没有选择项");	
		}
		ITenantService cataServ=(ITenantService) getService(TenantServiceImpl.class);
		String[] is=ids.split(",");
		String  whereString="from "+cataServ.getTableName()+" where ";
		for(String id:is){
			whereString+="id="+id+" or ";
		}
		whereString=whereString.substring(0,whereString.length()-4);
//		cataServ.getDao().clearCache();
		List<TenantEntity> ceList=cataServ.getList(whereString, null);
		for(TenantEntity t:ceList){
			if(t.getStatus().toString().equals(TenantEntity.TenantStatus_passed.toString())){
				t.setStatus(TenantEntity.TenantStatus_unPass);
//				String l=IbpdCommon.getInterface().getPropertiesValue("fileEncryptLength");
//				if(l==null)
//					throw new IbpdException("fileEncryptLength为空");
//				String tmpPath=t.getLicenceFilePath().substring(0,t.getLicenceFilePath().lastIndexOf("."))+"new"+t.getLicenceFilePath().substring(t.getLicenceFilePath().lastIndexOf("."));
//				FileEncryptAndDecryptUtil.decrypt(req.getRealPath(t.getLicenceFilePath().replace(req.getContextPath(), "")), req.getRealPath(tmpPath.replace(req.getContextPath(), "")),Integer.valueOf(l));
			}else if(t.getStatus().toString().equals(TenantEntity.TenantStatus_unPass.toString()) || !t.getStatus().toString().equals(TenantEntity.TenantStatus_passed.toString())){
				t.setStatus(TenantEntity.TenantStatus_passed);
				FileEncryptAndDecryptUtil.encrypt(req.getRealPath(t.getLicenceFilePath().replace(req.getContextPath(), "")), IbpdCommon.getInterface().getPropertiesValue("fileEncryptKey"));
			}else{
				t.setStatus(TenantEntity.TenantStatus_unPass);
//				String l=IbpdCommon.getInterface().getPropertiesValue("fileEncryptLength");
//				if(l==null)
//					throw new IbpdException("fileEncryptLength为空");
				//FileEncryptAndDecryptUtil.decrypt(req.getRealPath(t.getLicenceFilePath()), t.getLicenceFilePath(),Integer.valueOf(l));
			}
//			t.setStatus((t.getStatus()==TenantEntity.TenantStatus_passed?TenantEntity.TenantStatus_unPass:TenantEntity.TenantStatus_passed));
			cataServ.saveEntity(t);
		}
		super.printMsg(resp, "99", "", "操作成功");	
	}
}